class Song < ActiveRecord::Base
  has_and_belongs_to_many :artists
  belongs_to	:forum
  belongs_to	:song_collection
  belongs_to    :disc
  has_many	:song_credits, :dependent => :destroy
  has_many	:reviews, :as => :reviewable, :dependent => :destroy
  has_many	:images, :as => :photographable, :dependent => :destroy
  has_many	:edits, :as => :editable
  has_many	:versions, :through => :song_collection,
                           :source => :songs,
                           :order => "track"

  #Callbacks
  after_update :create_edit
  after_create :new_entry_edit
  before_create  :check_collection
  
  accepts_nested_attributes_for :song_collection

  attr_accessor :length_in_mins
  
  #
  #
  def to_s
    return title
  end

  #
  def to_param
    "#{id}-#{title.parameterize}"
  end

  def primary_image
    if images.empty?
      return nil
    else
      images.first.image
    end
  end
  
  def length_in_mins=(new_length)
    self.length = (new_length.partition(":").first.to_i * 60) + new_length.partition(":").last.to_i
  end
  
  def length_in_mins
    if length
      minutes = (length / 60).to_s
	  seconds = (length % 60).to_s
	
	  if seconds.to_i < 10
	    seconds = "0" + seconds
	  end
  
      return minutes + ":" + seconds
	else
	  return "0"
	end
	#length_in_mins
  end
  
  private
  
  #
  #
  def check_collection
    varient = Song.title_like(self.title)

     #check for similar songs, if so adds it to the
     # collection
    if !varient.empty?
      self.song_collection_id = varient.first.song_collection_id

    #otherwise start a new one
    else
      collection = SongCollection.new(:name => self.title)
      collection.save!
      self.song_collection_id = collection.id
    end
  end

  #
  #
  def new_entry_edit
    entry = Hash.new
    entry.store("created", [self.title])
    Edit.create_edit(entry, self)
  end

  #
  #
  def create_edit
    if self.changed?
      Edit.create_edit(self.changes, self)
    end
  end
end
